/**
 * API接口模拟和Mock数据
 */

// 模拟API响应延迟
const delay = (ms = 500) => new Promise(resolve => setTimeout(resolve, ms))

// 模拟API响应
const mockResponse = (data, success = true, message = '操作成功') => {
  return {
    code: success ? 200 : 400,
    message,
    data,
    timestamp: new Date().toISOString()
  }
}

// 模拟分页数据
const mockPagination = (data, page = 1, pageSize = 10) => {
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const items = data.slice(start, end)
  
  return {
    items,
    total: data.length,
    page,
    pageSize,
    totalPages: Math.ceil(data.length / pageSize)
  }
}

// 用户相关API
export const userAPI = {
  // 获取用户列表
  getUsers: async (params = {}) => {
    await delay()
    const users = [
      {
        id: 1,
        username: 'admin',
        name: '系统管理员',
        email: 'admin@example.com',
        phone: '13812345678',
        role: 'Administrator',
        status: '启用',
        remark: '系统最高权限用户',
        createTime: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        username: 'zhangsan',
        name: '张三',
        email: 'zhangsan@example.com',
        phone: '13987654321',
        role: 'User',
        status: '启用',
        remark: '普通销售人员',
        createTime: '2024-01-02 10:00:00'
      },
      {
        id: 3,
        username: 'lisi',
        name: '李四',
        email: 'lisi@example.com',
        phone: '13700001111',
        role: 'Guest',
        status: '禁用',
        remark: '临时访客账户',
        createTime: '2024-01-03 10:00:00'
      }
    ]
    
    const paginatedData = mockPagination(users, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },

  // 创建用户
  createUser: async (userData) => {
    await delay()
    const newUser = {
      id: Date.now(),
      ...userData,
      createTime: new Date().toLocaleString()
    }
    return mockResponse(newUser)
  },

  // 更新用户
  updateUser: async (id, userData) => {
    await delay()
    return mockResponse({ id, ...userData })
  },

  // 删除用户
  deleteUser: async (id) => {
    await delay()
    return mockResponse({ id })
  }
}

// 商品相关API
export const productAPI = {
  // 获取商品列表
  getProducts: async (params = {}) => {
    await delay()
    const products = [
      {
        id: 1,
        code: 'P001',
        name: 'iPhone 15',
        category: '电子产品',
        specification: '128GB 黑色',
        unit: '台',
        purchasePrice: 5000,
        salePrice: 5999,
        stock: 50,
        minStock: 10,
        maxStock: 100,
        status: '启用',
        createTime: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        code: 'P002',
        name: 'MacBook Pro',
        category: '电子产品',
        specification: '13英寸 M2芯片',
        unit: '台',
        purchasePrice: 12000,
        salePrice: 13999,
        stock: 30,
        minStock: 5,
        maxStock: 50,
        status: '启用',
        createTime: '2024-01-02 10:00:00'
      }
    ]
    
    const paginatedData = mockPagination(products, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },

  // 创建商品
  createProduct: async (productData) => {
    await delay()
    const newProduct = {
      id: Date.now(),
      ...productData,
      createTime: new Date().toLocaleString()
    }
    return mockResponse(newProduct)
  },

  // 更新商品
  updateProduct: async (id, productData) => {
    await delay()
    return mockResponse({ id, ...productData })
  },

  // 删除商品
  deleteProduct: async (id) => {
    await delay()
    return mockResponse({ id })
  }
}

// 供应商相关API
export const supplierAPI = {
  // 获取供应商列表
  getSuppliers: async (params = {}) => {
    await delay()
    const suppliers = [
      {
        id: 1,
        code: 'S001',
        name: '苹果供应商',
        contact: '张经理',
        phone: '13800138000',
        email: 'zhang@apple.com',
        address: '北京市朝阳区科技园区',
        category: '电子产品',
        status: '启用',
        remark: '苹果官方授权供应商',
        createTime: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        code: 'S002',
        name: '耐克供应商',
        contact: '李经理',
        phone: '13800138001',
        email: 'li@nike.com',
        address: '上海市浦东新区',
        category: '服装鞋帽',
        status: '启用',
        remark: '耐克品牌授权供应商',
        createTime: '2024-01-02 10:00:00'
      }
    ]
    
    const paginatedData = mockPagination(suppliers, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },

  // 创建供应商
  createSupplier: async (supplierData) => {
    await delay()
    const newSupplier = {
      id: Date.now(),
      ...supplierData,
      createTime: new Date().toLocaleString()
    }
    return mockResponse(newSupplier)
  },

  // 更新供应商
  updateSupplier: async (id, supplierData) => {
    await delay()
    return mockResponse({ id, ...supplierData })
  },

  // 删除供应商
  deleteSupplier: async (id) => {
    await delay()
    return mockResponse({ id })
  }
}

// 客户相关API
export const customerAPI = {
  // 获取客户列表
  getCustomers: async (params = {}) => {
    await delay()
    const customers = [
      {
        id: 1,
        code: 'C001',
        name: '张三',
        type: '个人客户',
        contact: '张三',
        phone: '13800138000',
        email: 'zhangsan@example.com',
        address: '北京市朝阳区',
        creditLimit: 50000,
        status: '启用',
        remark: '优质客户',
        createTime: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        code: 'C002',
        name: '北京科技有限公司',
        type: '企业客户',
        contact: '李经理',
        phone: '13800138001',
        email: 'li@company.com',
        address: '北京市海淀区中关村',
        creditLimit: 200000,
        status: '启用',
        remark: '长期合作客户',
        createTime: '2024-01-02 10:00:00'
      }
    ]
    
    const paginatedData = mockPagination(customers, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },

  // 创建客户
  createCustomer: async (customerData) => {
    await delay()
    const newCustomer = {
      id: Date.now(),
      ...customerData,
      createTime: new Date().toLocaleString()
    }
    return mockResponse(newCustomer)
  },

  // 更新客户
  updateCustomer: async (id, customerData) => {
    await delay()
    return mockResponse({ id, ...customerData })
  },

  // 删除客户
  deleteCustomer: async (id) => {
    await delay()
    return mockResponse({ id })
  }
}

// 采购订单相关API
export const purchaseOrderAPI = {
  // 获取采购订单列表
  getPurchaseOrders: async (params = {}) => {
    await delay()
    const orders = [
      {
        id: 1,
        orderNo: 'PO20240115001',
        supplierId: 1,
        supplierName: '苹果供应商',
        totalAmount: 25000,
        status: '已确认',
        createTime: '2024-01-15 10:00:00',
        expectedDate: '2024-01-20',
        buyer: '张三',
        remark: '紧急采购',
        products: [
          {
            productCode: 'P001',
            productName: 'iPhone 15',
            specification: '128GB 黑色',
            unit: '台',
            quantity: 5,
            unitPrice: 5000
          }
        ]
      }
    ]
    
    const paginatedData = mockPagination(orders, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },

  // 创建采购订单
  createPurchaseOrder: async (orderData) => {
    await delay()
    const newOrder = {
      id: Date.now(),
      ...orderData,
      status: '待确认',
      createTime: new Date().toLocaleString()
    }
    return mockResponse(newOrder)
  },

  // 更新采购订单
  updatePurchaseOrder: async (id, orderData) => {
    await delay()
    return mockResponse({ id, ...orderData })
  },

  // 确认采购订单
  confirmPurchaseOrder: async (id) => {
    await delay()
    return mockResponse({ id, status: '已确认' })
  },

  // 取消采购订单
  cancelPurchaseOrder: async (id) => {
    await delay()
    return mockResponse({ id, status: '已取消' })
  }
}

// 销售订单相关API
export const salesOrderAPI = {
  // 获取销售订单列表
  getSalesOrders: async (params = {}) => {
    await delay()
    const orders = [
      {
        id: 1,
        orderNo: 'SO20240115001',
        customerId: 1,
        customerName: '张三',
        totalAmount: 15000,
        status: '已完成',
        createTime: '2024-01-15 10:00:00',
        deliveryDate: '2024-01-16',
        salesman: '李四',
        remark: '客户要求加急',
        products: [
          {
            productCode: 'P001',
            productName: 'iPhone 15',
            specification: '128GB 黑色',
            unit: '台',
            quantity: 3,
            unitPrice: 5999
          }
        ]
      }
    ]
    
    const paginatedData = mockPagination(orders, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },

  // 创建销售订单
  createSalesOrder: async (orderData) => {
    await delay()
    const newOrder = {
      id: Date.now(),
      ...orderData,
      status: '待确认',
      createTime: new Date().toLocaleString()
    }
    return mockResponse(newOrder)
  },

  // 更新销售订单
  updateSalesOrder: async (id, orderData) => {
    await delay()
    return mockResponse({ id, ...orderData })
  },

  // 确认销售订单
  confirmSalesOrder: async (id) => {
    await delay()
    return mockResponse({ id, status: '已确认' })
  },

  // 取消销售订单
  cancelSalesOrder: async (id) => {
    await delay()
    return mockResponse({ id, status: '已取消' })
  }
}

// 库存相关API
export const inventoryAPI = {
  // 获取库存列表
  getInventory: async (params = {}) => {
    await delay()
    const inventory = [
      {
        id: 1,
        productId: 1,
        productCode: 'P001',
        productName: 'iPhone 15',
        warehouseId: 1,
        warehouseName: '主仓库',
        stock: 50,
        availableStock: 45,
        reservedStock: 5,
        minStock: 10,
        maxStock: 100,
        lastUpdateTime: '2024-01-15 10:00:00'
      },
      {
        id: 2,
        productId: 2,
        productCode: 'P002',
        productName: 'MacBook Pro',
        warehouseId: 1,
        warehouseName: '主仓库',
        stock: 30,
        availableStock: 25,
        reservedStock: 5,
        minStock: 5,
        maxStock: 50,
        lastUpdateTime: '2024-01-15 10:00:00'
      }
    ]
    
    const paginatedData = mockPagination(inventory, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },

  // 更新库存
  updateInventory: async (id, inventoryData) => {
    await delay()
    return mockResponse({ id, ...inventoryData })
  },

  // 库存调拨
  transferInventory: async (transferData) => {
    await delay()
    return mockResponse(transferData)
  }
}

// 审批相关API
export const approvalAPI = {
  // 获取审批列表
  getApprovals: async (params = {}) => {
    await delay()
    const approvals = [
      {
        id: 1,
        type: 'purchase_order',
        typeName: '采购订单审批',
        title: '采购订单审批',
        content: '订单号：PO20240115001，供应商：苹果供应商，金额：¥25,000',
        applicant: '张三',
        applicantId: 1,
        createTime: '2024-01-15 10:00:00',
        priority: 'high',
        amount: 25000,
        orderId: 1,
        orderNo: 'PO20240115001',
        status: 'pending',
        currentStep: 1,
        totalSteps: 2,
        approvers: [
          { id: 1, name: '李经理', role: '采购经理', status: 'pending', approveTime: null, comment: '' },
          { id: 2, name: '王总', role: '总经理', status: 'pending', approveTime: null, comment: '' }
        ]
      }
    ]
    
    const paginatedData = mockPagination(approvals, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },

  // 提交审批
  submitApproval: async (approvalData) => {
    await delay()
    const newApproval = {
      id: Date.now(),
      ...approvalData,
      status: 'pending',
      createTime: new Date().toLocaleString()
    }
    return mockResponse(newApproval)
  },

  // 审批通过
  approveApproval: async (id, approverId, comment) => {
    await delay()
    return mockResponse({ id, approverId, comment, status: 'approved' })
  },

  // 审批拒绝
  rejectApproval: async (id, approverId, comment) => {
    await delay()
    return mockResponse({ id, approverId, comment, status: 'rejected' })
  }
}

// 系统设置相关API
export const systemAPI = {
  // 获取系统设置
  getSettings: async (type) => {
    await delay()
    const settings = {
      basic: {
        systemName: '大型ERP管理系统',
        systemVersion: '1.0.0',
        companyName: '示例科技有限公司',
        companyAddress: '北京市朝阳区科技园区',
        companyPhone: '400-123-4567',
        companyEmail: 'contact@example.com',
        companyWebsite: 'https://www.example.com'
      },
      business: {
        defaultWarehouse: '1',
        stockWarningThreshold: 10,
        autoGenerateCode: true,
        orderPrefix: 'PO',
        orderValidityDays: 30,
        autoConfirmOrder: false,
        defaultCurrency: 'CNY',
        taxRate: 13.00
      },
      security: {
        passwordMinLength: 8,
        passwordComplexity: ['uppercase', 'lowercase', 'numbers'],
        passwordExpiryDays: 90,
        loginLockEnabled: true,
        maxLoginAttempts: 5,
        lockoutDuration: 30,
        sessionTimeout: 120,
        dataEncryption: true,
        operationLog: true
      }
    }
    
    return mockResponse(settings[type] || {})
  },

  // 更新系统设置
  updateSettings: async (type, settings) => {
    await delay()
    return mockResponse({ type, settings })
  }
}

// 统计相关API
export const statisticsAPI = {
  // 获取仪表板数据
  getDashboardData: async () => {
    await delay()
    const data = {
      salesTrend: {
        labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
        data: [12000, 15000, 18000, 22000, 25000, 28000]
      },
      categoryDistribution: [
        { name: '电子产品', value: 35 },
        { name: '服装鞋帽', value: 25 },
        { name: '家居用品', value: 20 },
        { name: '食品饮料', value: 15 },
        { name: '其他', value: 5 }
      ],
      recentActivities: [
        {
          id: 1,
          type: 'purchase',
          title: '完成采购订单 PO20240115001',
          user: '张三',
          time: '2024/01/15 10:00'
        },
        {
          id: 2,
          type: 'customer',
          title: '新增客户 北京科技有限公司',
          user: '李四',
          time: '2024/01/14 14:30'
        },
        {
          id: 3,
          type: 'inventory',
          title: '更新商品库存 iPhone 15',
          user: '王五',
          time: '2024/01/13 11:00'
        }
      ]
    }
    
    return mockResponse(data)
  },

  // 获取销售统计
  getSalesStatistics: async (params = {}) => {
    await delay()
    const data = {
      totalSales: 1250000,
      totalOrders: 1250,
      avgOrderValue: 1000,
      growthRate: 15.5
    }
    
    return mockResponse(data)
  },

  // 获取库存统计
  getInventoryStatistics: async () => {
    await delay()
    const data = {
      totalProducts: 1250,
      totalValue: 2500000,
      lowStockProducts: 25,
      outOfStockProducts: 5
    }
    
    return mockResponse(data)
  }
}

// 文件上传API
export const uploadAPI = {
  // 上传文件
  uploadFile: async (file) => {
    await delay(1000) // 模拟上传时间
    const filename = `upload_${Date.now()}_${file.name}`
    return mockResponse({ filename, url: `/uploads/${filename}` })
  }
}

// 办公管理 - 公告相关API
export const announcementAPI = {
  // 获取公告列表
  getAnnouncements: async (params = {}) => {
    await delay()
    const announcements = [
      {
        id: 1,
        title: '关于2024年春节放假通知',
        type: 'notice',
        content: '根据国家规定，2024年春节放假时间为...',
        publisher: '张三',
        publishTime: '2024-01-15 10:30:00',
        views: 1256,
        status: 'published',
        isTop: true,
        scope: 'all'
      }
    ]
    const paginatedData = mockPagination(announcements, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 创建公告
  createAnnouncement: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data })
  },
  
  // 更新公告
  updateAnnouncement: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 删除公告
  deleteAnnouncement: async (id) => {
    await delay()
    return mockResponse({ id })
  }
}

// 办公管理 - 通知相关API
export const notificationAPI = {
  // 获取通知列表
  getNotifications: async (params = {}) => {
    await delay()
    const notifications = [
      {
        id: 1,
        type: 'system',
        title: '系统维护通知',
        content: '系统将于今晚22:00-24:00进行升级维护...',
        sender: '系统管理员',
        time: '2024-01-15 10:30:00',
        isRead: false,
        link: true
      }
    ]
    const paginatedData = mockPagination(notifications, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 标记已读
  markAsRead: async (id) => {
    await delay()
    return mockResponse({ id, isRead: true })
  },
  
  // 全部标记为已读
  markAllAsRead: async () => {
    await delay()
    return mockResponse({ success: true })
  }
}

// 办公管理 - 日程相关API
export const scheduleAPI = {
  // 获取日程列表
  getSchedules: async (params = {}) => {
    await delay()
    const schedules = [
      {
        id: 1,
        title: '项目进度会议',
        type: 'meeting',
        date: '2024-01-18',
        startTime: '09:00',
        endTime: '10:30',
        location: '会议室A',
        participants: ['张三', '李四', '王五'],
        reminder: '15'
      }
    ]
    return mockResponse(schedules)
  },
  
  // 创建日程
  createSchedule: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data })
  },
  
  // 更新日程
  updateSchedule: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 删除日程
  deleteSchedule: async (id) => {
    await delay()
    return mockResponse({ id })
  }
}

// 办公管理 - 任务相关API
export const taskAPI = {
  // 获取任务列表
  getTasks: async (params = {}) => {
    await delay()
    const tasks = [
      {
        id: 1,
        title: '完成项目需求文档',
        priority: 'high',
        status: 'processing',
        assignee: '张三',
        creator: '李四',
        deadline: '2024-01-20',
        progress: 60,
        description: '完成相关工作...'
      }
    ]
    const paginatedData = mockPagination(tasks, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 创建任务
  createTask: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data, status: 'pending', progress: 0 })
  },
  
  // 更新任务
  updateTask: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 删除任务
  deleteTask: async (id) => {
    await delay()
    return mockResponse({ id })
  },
  
  // 完成任务
  completeTask: async (id) => {
    await delay()
    return mockResponse({ id, status: 'completed', progress: 100 })
  }
}

// 办公管理 - 文档相关API
export const documentAPI = {
  // 获取文档列表
  getDocuments: async (params = {}) => {
    await delay()
    const documents = [
      {
        id: 1,
        name: '项目需求文档.docx',
        type: 'word',
        size: '2.5 MB',
        owner: '张三',
        time: '2024-01-15 10:30',
        folderId: 1
      }
    ]
    return mockResponse(documents)
  },
  
  // 上传文档
  uploadDocument: async (file, folderId) => {
    await delay(1000)
    return mockResponse({ 
      id: Date.now(),
      name: file.name,
      size: file.size,
      time: new Date().toLocaleString()
    })
  },
  
  // 删除文档
  deleteDocument: async (id) => {
    await delay()
    return mockResponse({ id })
  },
  
  // 获取文件夹树
  getFolderTree: async () => {
    await delay()
    const tree = [
      {
        id: 1,
        name: '我的文档',
        children: [
          { id: 11, name: '工作文档' },
          { id: 12, name: '个人文件' }
        ]
      }
    ]
    return mockResponse(tree)
  }
}

// 办公管理 - 会议相关API
export const meetingAPI = {
  // 获取会议列表
  getMeetings: async (params = {}) => {
    await delay()
    const meetings = [
      {
        id: 1,
        title: '月度工作总结会',
        room: '会议室A',
        roomId: 1,
        date: '2024-01-18',
        startTime: '14:00',
        endTime: '16:00',
        organizer: '张三',
        attendees: ['李四', '王五'],
        status: 'upcoming',
        agenda: '会议议程...'
      }
    ]
    const paginatedData = mockPagination(meetings, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 获取会议室列表
  getMeetingRooms: async () => {
    await delay()
    const rooms = [
      {
        id: 1,
        name: '会议室A',
        capacity: 20,
        location: '1楼',
        status: 'available',
        equipment: ['投影仪', '白板', '视频会议']
      }
    ]
    return mockResponse(rooms)
  },
  
  // 预定会议
  bookMeeting: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data, status: 'upcoming' })
  },
  
  // 取消会议
  cancelMeeting: async (id) => {
    await delay()
    return mockResponse({ id, status: 'cancelled' })
  }
}

// 办公管理 - 审批相关API（扩展）
export const officeApprovalAPI = {
  // 获取审批列表
  getApprovals: async (params = {}) => {
    await delay()
    const approvals = [
      {
        id: 'AP2024011501',
        title: '请假申请-年假',
        type: 'leave',
        initiator: '张三',
        currentApprover: '李四',
        createTime: '2024-01-15 09:00',
        status: 'pending',
        content: '申请内容...'
      }
    ]
    const paginatedData = mockPagination(approvals, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 提交审批
  submitApproval: async (data) => {
    await delay()
    return mockResponse({ id: 'AP' + Date.now(), ...data, status: 'pending' })
  },
  
  // 审批通过
  approveApproval: async (id, comment) => {
    await delay()
    return mockResponse({ id, status: 'approved', comment })
  },
  
  // 审批拒绝
  rejectApproval: async (id, comment) => {
    await delay()
    return mockResponse({ id, status: 'rejected', comment })
  },
  
  // 撤回审批
  revokeApproval: async (id) => {
    await delay()
    return mockResponse({ id, status: 'revoked' })
  }
}

// 办公管理 - 通讯录相关API
export const contactAPI = {
  // 获取联系人列表
  getContacts: async (params = {}) => {
    await delay()
    const contacts = [
      {
        id: 1,
        name: '张三',
        position: '技术总监',
        department: '技术部',
        phone: '138****0001',
        email: 'zhangsan@company.com',
        workLocation: '北京总部',
        employeeId: 'EMP001',
        supervisor: '李总'
      }
    ]
    return mockResponse(contacts)
  },
  
  // 获取组织架构树
  getOrgTree: async () => {
    await delay()
    const tree = [
      {
        id: 1,
        name: '公司总部',
        count: 24,
        children: [
          { id: 11, name: '技术部', count: 8 },
          { id: 12, name: '产品部', count: 6 }
        ]
      }
    ]
    return mockResponse(tree)
  },
  
  // 添加联系人
  createContact: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data })
  },
  
  // 更新联系人
  updateContact: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  }
}

// 办公管理 - 工作日志相关API
export const workLogAPI = {
  // 获取工作日志列表
  getWorkLogs: async (params = {}) => {
    await delay()
    const logs = [
      {
        id: 1,
        author: '张三',
        date: '2024-01-15',
        time: '18:30',
        completedTasks: ['完成用户登录功能开发', '修复数据统计bug'],
        plannedTasks: ['开发用户权限管理模块'],
        issues: '在测试环境发现部分接口响应较慢',
        workHours: 8.5,
        commentCount: 2
      }
    ]
    const paginatedData = mockPagination(logs, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 提交工作日志
  submitWorkLog: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data, commentCount: 0 })
  },
  
  // 更新工作日志
  updateWorkLog: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 添加评论
  addComment: async (logId, comment) => {
    await delay()
    return mockResponse({ logId, comment })
  }
}

// 办公管理 - 邮件相关API
export const emailAPI = {
  // 获取邮件列表
  getEmails: async (params = {}) => {
    await delay()
    const emails = [
      {
        id: 1,
        folder: 'inbox',
        from: '张三',
        fromEmail: 'zhangsan@company.com',
        to: '我',
        subject: '关于项目进度的讨论',
        preview: '您好，我想和您讨论一下当前项目的进度情况...',
        content: '<p>您好，</p><p>我想和您讨论一下当前项目的进度情况...</p>',
        time: '10:30',
        fullTime: '2024-01-15 10:30:25',
        isRead: false,
        starred: false,
        hasAttachment: true,
        attachments: [{ name: '项目计划.docx', size: '2.5 MB' }]
      }
    ]
    return mockResponse(emails)
  },
  
  // 发送邮件
  sendEmail: async (data) => {
    await delay(1000)
    return mockResponse({ id: Date.now(), ...data, folder: 'sent' })
  },
  
  // 保存草稿
  saveDraft: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data, folder: 'draft' })
  },
  
  // 删除邮件
  deleteEmail: async (id) => {
    await delay()
    return mockResponse({ id })
  },
  
  // 标记星标
  toggleStar: async (id, starred) => {
    await delay()
    return mockResponse({ id, starred })
  }
}

// 学习管理 - 课程相关API
export const courseAPI = {
  // 获取课程列表
  getCourses: async (params = {}) => {
    await delay()
    const courses = [
      {
        id: 1,
        title: 'Vue 3 从入门到精通',
        description: '全面学习Vue 3框架，掌握Composition API和TypeScript',
        category: 'tech',
        categoryName: '技术开发',
        teacher: '张三',
        duration: '30小时',
        lessonsCount: 45,
        studentCount: 1256,
        rating: 4.8,
        difficulty: '中级',
        isNew: true,
        isHot: true,
        enrolled: false
      }
    ]
    const paginatedData = mockPagination(courses, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 报名课程
  enrollCourse: async (courseId) => {
    await delay()
    return mockResponse({ courseId, enrolled: true })
  },
  
  // 获取课程详情
  getCourseDetail: async (courseId) => {
    await delay()
    return mockResponse({ id: courseId, chapters: [] })
  }
}

// 学习管理 - 学习记录相关API
export const studyRecordAPI = {
  // 获取学习记录
  getStudyRecords: async (params = {}) => {
    await delay()
    const records = [
      {
        id: 1,
        courseName: 'Vue 3 从入门到精通',
        type: 'study',
        content: '学习了"Composition API详解"章节',
        duration: '45分钟',
        time: '2024-01-15 10:30'
      }
    ]
    return mockResponse(records)
  },
  
  // 获取学习统计
  getStudyStats: async () => {
    await delay()
    return mockResponse({
      totalHours: 156,
      completedCourses: 12,
      certificates: 8,
      points: 2580
    })
  }
}

// 学习管理 - 考试相关API
export const examAPI = {
  // 获取考试列表
  getExams: async (params = {}) => {
    await delay()
    const exams = [
      {
        id: 1,
        title: 'Vue 3 基础知识测验',
        courseName: 'Vue 3 从入门到精通',
        type: 'quiz',
        totalScore: 100,
        passScore: 60,
        duration: '60分钟',
        startTime: '2024-01-15 09:00',
        endTime: '2024-01-20 18:00',
        status: 'pending'
      }
    ]
    const paginatedData = mockPagination(exams, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 开始考试
  startExam: async (examId) => {
    await delay()
    return mockResponse({ examId, questions: [] })
  },
  
  // 提交考试
  submitExam: async (examId, answers) => {
    await delay()
    return mockResponse({ examId, score: 95, passed: true })
  },
  
  // 获取考试结果
  getExamResult: async (examId) => {
    await delay()
    return mockResponse({ examId, score: 95, passed: true })
  }
}

// 学习管理 - 证书相关API
export const certificateAPI = {
  // 获取证书列表
  getCertificates: async (params = {}) => {
    await delay()
    const certificates = [
      {
        id: 1,
        certNo: 'CERT2024010001',
        courseName: 'Vue 3 从入门到精通',
        holderName: '张三',
        score: 95,
        level: 'gold',
        issueDate: '2024-01-12'
      }
    ]
    return mockResponse(certificates)
  },
  
  // 下载证书
  downloadCertificate: async (certId) => {
    await delay()
    return mockResponse({ certId, url: '/certificates/' + certId + '.pdf' })
  }
}

// 学习管理 - 知识库相关API
export const knowledgeAPI = {
  // 获取文章列表
  getArticles: async (params = {}) => {
    await delay()
    const articles = [
      {
        id: 1,
        title: 'Vue 3 Composition API 最佳实践',
        summary: '深入探讨Vue 3 Composition API的使用技巧...',
        author: '张三',
        publishTime: '2024-01-15',
        views: 1256,
        likes: 89,
        tags: ['Vue', '前端开发'],
        categoryId: 1
      }
    ]
    const paginatedData = mockPagination(articles, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 创建文章
  createArticle: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data })
  },
  
  // 点赞文章
  likeArticle: async (articleId) => {
    await delay()
    return mockResponse({ articleId, liked: true })
  },
  
  // 获取分类
  getCategories: async () => {
    await delay()
    return mockResponse([
      { id: 1, name: '技术文档', count: 12 },
      { id: 2, name: '产品知识', count: 8 }
    ])
  }
}

// 学习管理 - 培训计划相关API
export const trainingPlanAPI = {
  // 获取培训计划列表
  getTrainingPlans: async (params = {}) => {
    await delay()
    const plans = [
      {
        id: 1,
        name: '2024年新员工入职培训',
        type: 'onboarding',
        participants: 25,
        startDate: '2024-01-15',
        endDate: '2024-02-15',
        progress: 60,
        status: 'ongoing'
      }
    ]
    const paginatedData = mockPagination(plans, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 创建培训计划
  createTrainingPlan: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data })
  },
  
  // 更新培训计划
  updateTrainingPlan: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 删除培训计划
  deleteTrainingPlan: async (id) => {
    await delay()
    return mockResponse({ id })
  }
}

// 学习管理 - 排行榜相关API
export const learningRankingAPI = {
  // 获取学习排行榜
  getRankings: async (params = {}) => {
    await delay()
    const rankings = [
      {
        rank: 1,
        name: '张三',
        department: '技术部',
        value: 156,
        coursesCompleted: 12,
        totalHours: 156,
        points: 2580,
        trend: 2
      }
    ]
    return mockResponse(rankings)
  }
}

// 学习管理 - 课程管理API（管理员）
export const courseManageAPI = {
  // 获取课程管理列表
  getManageCourses: async (params = {}) => {
    await delay()
    const courses = [
      {
        id: 1,
        title: 'Vue 3 从入门到精通',
        categoryName: '技术开发',
        category: 'tech',
        teacher: '张三',
        lessonsCount: 45,
        studentCount: 1256,
        rating: 4.8,
        status: 'published'
      }
    ]
    const paginatedData = mockPagination(courses, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 创建课程
  createCourse: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data })
  },
  
  // 更新课程
  updateCourse: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 删除课程
  deleteCourse: async (id) => {
    await delay()
    return mockResponse({ id })
  },
  
  // 发布课程
  publishCourse: async (id) => {
    await delay()
    return mockResponse({ id, status: 'published' })
  },
  
  // 下架课程
  offlineCourse: async (id) => {
    await delay()
    return mockResponse({ id, status: 'offline' })
  }
}

// 学习管理 - 考试管理API
export const examManageAPI = {
  // 获取试卷列表
  getExamPapers: async (params = {}) => {
    await delay()
    const papers = [
      {
        id: 1,
        title: 'Vue 3 基础知识测验',
        courseName: 'Vue 3 从入门到精通',
        type: 'quiz',
        questionCount: 20,
        totalScore: 100,
        duration: '60分钟',
        status: 'published'
      }
    ]
    const paginatedData = mockPagination(papers, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 创建试卷
  createExamPaper: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data })
  },
  
  // 更新试卷
  updateExamPaper: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 删除试卷
  deleteExamPaper: async (id) => {
    await delay()
    return mockResponse({ id })
  }
}

// 学习管理 - 题库管理API
export const questionBankAPI = {
  // 获取题目列表
  getQuestions: async (params = {}) => {
    await delay()
    const questions = [
      {
        id: 1,
        content: 'Vue 3 的 Composition API 中，ref 和 reactive 的区别是什么？',
        type: 'single',
        difficulty: '中等',
        score: 5,
        category: 'Vue基础',
        useCount: 12
      }
    ]
    const paginatedData = mockPagination(questions, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 创建题目
  createQuestion: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data })
  },
  
  // 更新题目
  updateQuestion: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 删除题目
  deleteQuestion: async (id) => {
    await delay()
    return mockResponse({ id })
  }
}

// 学习管理 - 讲师管理API
export const teacherManageAPI = {
  // 获取讲师列表
  getTeachers: async (params = {}) => {
    await delay()
    const teachers = [
      {
        id: 1,
        name: '张三',
        title: '高级前端工程师',
        specialty: '前端开发',
        coursesCount: 8,
        studentsCount: 2456,
        rating: 4.9,
        isFeatured: true,
        status: 'active'
      }
    ]
    const paginatedData = mockPagination(teachers, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 创建讲师
  createTeacher: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data })
  },
  
  // 更新讲师
  updateTeacher: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 删除讲师
  deleteTeacher: async (id) => {
    await delay()
    return mockResponse({ id })
  },
  
  // 设置金牌讲师
  toggleFeatured: async (id, isFeatured) => {
    await delay()
    return mockResponse({ id, isFeatured })
  }
}

// 学习管理 - 学习设置API
export const learningSettingsAPI = {
  // 获取学习设置
  getSettings: async (type) => {
    await delay()
    const settings = {
      basic: {},
      exam: {},
      certificate: {},
      points: {}
    }
    return mockResponse(settings[type] || {})
  },
  
  // 更新学习设置
  updateSettings: async (type, data) => {
    await delay()
    return mockResponse({ type, data })
  }
}

// 办公管理 - 待办事项相关API
export const todoAPI = {
  // 获取待办列表
  getTodos: async (params = {}) => {
    await delay()
    const todos = [
      {
        id: 1,
        title: '完成项目需求文档',
        description: '整理并完成项目的需求文档',
        categoryId: 1,
        categoryName: '工作',
        categoryColor: '#409EFF',
        priority: 'high',
        dueDate: '2024-01-18 18:00',
        reminder: '60',
        important: true,
        completed: false,
        createTime: '2024-01-15 09:00'
      }
    ]
    const paginatedData = mockPagination(todos, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 创建待办
  createTodo: async (data) => {
    await delay()
    return mockResponse({ 
      id: Date.now(), 
      ...data, 
      completed: false,
      createTime: new Date().toLocaleString()
    })
  },
  
  // 更新待办
  updateTodo: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 删除待办
  deleteTodo: async (id) => {
    await delay()
    return mockResponse({ id })
  },
  
  // 完成/取消完成待办
  toggleComplete: async (id, completed) => {
    await delay()
    return mockResponse({ id, completed })
  },
  
  // 标记/取消重要
  toggleImportant: async (id, important) => {
    await delay()
    return mockResponse({ id, important })
  },
  
  // 获取分类列表
  getCategories: async () => {
    await delay()
    const categories = [
      { id: 1, name: '工作', color: '#409EFF', count: 5 },
      { id: 2, name: '生活', color: '#67C23A', count: 3 },
      { id: 3, name: '学习', color: '#E6A23C', count: 2 }
    ]
    return mockResponse(categories)
  },
  
  // 创建分类
  createCategory: async (data) => {
    await delay()
    return mockResponse({ id: Date.now(), ...data, count: 0 })
  },
  
  // 清除已完成
  clearCompleted: async () => {
    await delay()
    return mockResponse({ success: true })
  }
}

// 待办看板 API
export const todoBoardAPI = {
  // 获取看板数据
  getBoardItems: async (params = {}) => {
    await delay()
    const boardItems = [
      {
        id: 1,
        title: '完成项目需求文档',
        description: '整理并完成项目的需求文档',
        status: 'backlog',
        categoryId: 1,
        categoryName: '工作',
        categoryColor: '#409EFF',
        priority: 'high',
        dueDate: '2024-01-18 18:00',
        important: true,
        progress: 0,
        createTime: '2024-01-15 09:00'
      },
      {
        id: 2,
        title: '开发用户管理模块',
        description: '完成用户增删改查功能',
        status: 'inProgress',
        categoryId: 1,
        categoryName: '工作',
        categoryColor: '#409EFF',
        priority: 'urgent',
        dueDate: '2024-01-20 18:00',
        important: true,
        progress: 65,
        createTime: '2024-01-14 10:00'
      },
      {
        id: 3,
        title: '代码审查',
        description: '审查团队成员的PR',
        status: 'review',
        categoryId: 1,
        categoryName: '工作',
        categoryColor: '#409EFF',
        priority: 'normal',
        dueDate: '2024-01-17 16:00',
        important: false,
        createTime: '2024-01-15 11:00'
      },
      {
        id: 4,
        title: '买菜做饭',
        description: '晚餐食材采购',
        status: 'completed',
        categoryId: 2,
        categoryName: '生活',
        categoryColor: '#67C23A',
        priority: 'normal',
        dueDate: '2024-01-15 18:00',
        important: false,
        completedDate: '2024-01-15 17:30',
        createTime: '2024-01-15 08:00'
      }
    ]
    
    // 根据状态筛选
    let filteredItems = boardItems
    if (params.status) {
      filteredItems = boardItems.filter(item => item.status === params.status)
    }
    
    return mockResponse(filteredItems)
  },
  
  // 创建看板项
  createBoardItem: async (data) => {
    await delay()
    return mockResponse({ 
      id: Date.now(), 
      ...data,
      progress: data.status === 'inProgress' ? 0 : undefined,
      createTime: new Date().toLocaleString()
    })
  },
  
  // 更新看板项
  updateBoardItem: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 删除看板项
  deleteBoardItem: async (id) => {
    await delay()
    return mockResponse({ id })
  },
  
  // 移动看板项（改变状态）
  moveBoardItem: async (id, newStatus) => {
    await delay()
    const response = { 
      id, 
      status: newStatus
    }
    
    // 如果移到已完成，添加完成时间
    if (newStatus === 'completed') {
      response.completedDate = new Date().toLocaleString()
    }
    
    // 如果移到进行中，初始化进度
    if (newStatus === 'inProgress') {
      response.progress = 0
    }
    
    return mockResponse(response)
  },
  
  // 更新进度
  updateProgress: async (id, progress) => {
    await delay()
    return mockResponse({ id, progress })
  },
  
  // 获取看板统计
  getBoardStats: async () => {
    await delay()
    return mockResponse({
      backlog: 5,
      inProgress: 3,
      review: 2,
      completed: 8,
      total: 18
    })
  },
  
  // 批量移动
  batchMove: async (ids, newStatus) => {
    await delay()
    return mockResponse({ ids, status: newStatus })
  },
  
  // 清除已完成
  clearCompleted: async () => {
    await delay()
    return mockResponse({ success: true })
  }
}

// 库存盘点 - 盘点任务 API
export const checkTaskAPI = {
  // 获取盘点任务列表
  getTasks: async (params = {}) => {
    await delay()
    const tasks = [
      {
        id: 1,
        taskNo: 'CHK202401150001',
        taskName: '2024年1月全盘任务',
        type: 'full',
        warehouseId: 1,
        warehouseName: '主仓库',
        status: 'inProgress',
        planStartDate: '2024-01-15 08:00:00',
        planEndDate: '2024-01-17 18:00:00',
        actualStartDate: '2024-01-15 08:30:00',
        actualEndDate: null,
        responsiblePerson: '张三',
        progress: 65,
        remark: '年度全盘任务',
        createTime: '2024-01-14 10:00:00'
      }
    ]
    const paginatedData = mockPagination(tasks, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 创建盘点任务
  createTask: async (data) => {
    await delay()
    return mockResponse({
      id: Date.now(),
      taskNo: 'CHK' + Date.now(),
      ...data,
      status: 'pending',
      progress: 0,
      createTime: new Date().toLocaleString()
    })
  },
  
  // 更新盘点任务
  updateTask: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 删除盘点任务
  deleteTask: async (id) => {
    await delay()
    return mockResponse({ id })
  },
  
  // 开始盘点
  startCheck: async (id) => {
    await delay()
    return mockResponse({
      id,
      status: 'inProgress',
      actualStartDate: new Date().toLocaleString()
    })
  },
  
  // 完成盘点
  completeCheck: async (id) => {
    await delay()
    return mockResponse({
      id,
      status: 'completed',
      actualEndDate: new Date().toLocaleString(),
      progress: 100
    })
  },
  
  // 取消盘点
  cancelTask: async (id) => {
    await delay()
    return mockResponse({ id, status: 'cancelled' })
  }
}

// 库存盘点 - 盘点单 API
export const checkSheetAPI = {
  // 获取盘点单列表
  getSheets: async (params = {}) => {
    await delay()
    const sheets = [
      {
        id: 1,
        sheetNo: 'CHS202401150001',
        taskNo: 'CHK202401150001',
        taskId: 1,
        warehouseId: 1,
        warehouseName: '主仓库',
        status: 'completed',
        checkPerson: '张三',
        checkTime: '2024-01-15 14:30:00',
        totalItems: 5,
        totalDiffQty: -15,
        totalDiffAmount: -4500,
        remark: '',
        createTime: '2024-01-15 08:30:00',
        items: []
      }
    ]
    const paginatedData = mockPagination(sheets, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 创建盘点单
  createSheet: async (data) => {
    await delay()
    return mockResponse({
      id: Date.now(),
      sheetNo: 'CHS' + Date.now(),
      ...data,
      status: 'pending',
      totalItems: 0,
      totalDiffQty: 0,
      totalDiffAmount: 0,
      createTime: new Date().toLocaleString(),
      items: []
    })
  },
  
  // 更新盘点单
  updateSheet: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 删除盘点单
  deleteSheet: async (id) => {
    await delay()
    return mockResponse({ id })
  },
  
  // 审核盘点单
  approveSheet: async (id) => {
    await delay()
    return mockResponse({ id, status: 'approved' })
  },
  
  // 获取盘点单详情
  getSheetDetail: async (id) => {
    await delay()
    return mockResponse({
      id,
      sheetNo: 'CHS202401150001',
      items: []
    })
  }
}

// 库存盘点 - 盈亏分析 API
export const profitLossAPI = {
  // 获取盈亏统计
  getStats: async (params = {}) => {
    await delay()
    return mockResponse({
      totalProfit: 125000,
      profitCount: 45,
      totalLoss: 98500,
      lossCount: 38,
      netAmount: 26500,
      profitLossRate: 1.2,
      totalProducts: 156,
      totalSheets: 28
    })
  },
  
  // 获取盈亏汇总数据
  getSummaryData: async (params = {}) => {
    await delay()
    const summaryData = [
      {
        productCode: 'P001',
        productName: 'iPhone 15 Pro Max 256GB',
        category: '手机',
        checkCount: 3,
        totalDiffQty: -12,
        unitPrice: 9999,
        totalDiffAmount: -119988,
        lossRate: 2.4
      }
    ]
    const paginatedData = mockPagination(summaryData, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 获取盈亏明细数据
  getDetailData: async (params = {}) => {
    await delay()
    const detailData = [
      {
        sheetNo: 'CHS202401150001',
        checkTime: '2024-01-15 14:30:00',
        warehouseName: '主仓库',
        productCode: 'P001',
        productName: 'iPhone 15 Pro Max 256GB',
        bookQty: 100,
        actualQty: 95,
        diffQty: -5,
        unitPrice: 9999,
        diffAmount: -49995,
        checkPerson: '张三',
        remark: '发现破损2台，丢失3台'
      }
    ]
    const paginatedData = mockPagination(detailData, params.page, params.pageSize)
    return mockResponse(paginatedData)
  }
}

// 库存盘点 - 盈亏策略 API
export const profitLossStrategyAPI = {
  // 获取策略列表
  getStrategies: async () => {
    await delay()
    return mockResponse([
      {
        id: 1,
        name: '大额盘盈自动入库',
        type: 'profit',
        condition: '盘盈金额 > 5000元',
        action: '自动生成入库单，更新库存',
        status: true,
        priority: 1,
        updateTime: '2024-01-15 10:00:00'
      }
    ])
  },
  
  // 创建策略
  createStrategy: async (data) => {
    await delay()
    return mockResponse({
      id: Date.now(),
      ...data,
      updateTime: new Date().toLocaleString()
    })
  },
  
  // 更新策略
  updateStrategy: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },
  
  // 删除策略
  deleteStrategy: async (id) => {
    await delay()
    return mockResponse({ id })
  },
  
  // 启用/禁用策略
  toggleStatus: async (id, status) => {
    await delay()
    return mockResponse({ id, status })
  }
}

// 库存盘点 - 预盈库 API
export const preInventoryAPI = {
  // 获取预盈库数据
  getPreInventory: async (params = {}) => {
    await delay()
    const data = [
      {
        id: 1,
        sheetNo: 'CHS202401150001',
        warehouseId: 1,
        warehouseName: '主仓库',
        productCode: 'P003',
        productName: 'AirPods Pro 2',
        profitQty: 5,
        unitPrice: 1899,
        totalAmount: 9495,
        checkTime: '2024-01-15 14:30:00',
        status: 'pending'
      }
    ]
    const paginatedData = mockPagination(data, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },
  
  // 获取统计信息
  getStats: async () => {
    await delay()
    return mockResponse({
      totalItems: 15,
      totalQty: 238,
      totalAmount: 456800
    })
  },
  
  // 单个入库
  processItem: async (id) => {
    await delay()
    return mockResponse({ id, status: 'processed' })
  },
  
  // 批量入库
  batchProcess: async (ids) => {
    await delay()
    return mockResponse({ ids, success: true })
  }
}

// 售后管理 API
export const aftersalesAPI = {
  // 获取售后单列表
  getAftersalesList: async (params = {}) => {
    await delay()
    const data = [
      {
        id: 1,
        afterSalesNo: 'AS202501190001',
        orderNo: 'SO202501150234',
        type: '退货退款',
        customerName: '张三',
        productName: '华为 Mate 60 Pro 12GB+512GB',
        quantity: 1,
        refundAmount: 6999.00,
        status: '待审核',
        reason: '质量问题',
        phone: '13800138000',
        refundMethod: '原路退回',
        description: '手机屏幕有划痕',
        applyTime: '2025-01-19 10:30:00',
        items: [
          {
            productName: '华为 Mate 60 Pro 12GB+512GB',
            specification: '曜金黑',
            quantity: 1,
            unitPrice: 6999.00,
            maxQuantity: 1
          }
        ]
      }
    ]
    const paginatedData = mockPagination(data, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },

  // 获取售后统计
  getStatistics: async () => {
    await delay()
    return mockResponse({
      total: 156,
      pending: 23,
      completed: 118,
      refundAmount: 45680.50
    })
  },

  // 创建售后单
  createAftersales: async (data) => {
    await delay()
    return mockResponse({
      id: Date.now(),
      afterSalesNo: 'AS' + Date.now(),
      ...data,
      status: '待审核',
      applyTime: new Date().toLocaleString()
    })
  },

  // 更新售后单
  updateAftersales: async (id, data) => {
    await delay()
    return mockResponse({ id, ...data })
  },

  // 删除售后单
  deleteAftersales: async (id) => {
    await delay()
    return mockResponse({ id })
  },

  // 审核售后单
  approveAftersales: async (id, data) => {
    await delay()
    return mockResponse({
      id,
      status: data.result === '通过' ? '审核通过' : '审核拒绝',
      approveTime: new Date().toLocaleString(),
      ...data
    })
  },

  // 获取售后详情
  getAftersalesDetail: async (id) => {
    await delay()
    return mockResponse({
      id,
      afterSalesNo: 'AS202501190001',
      orderNo: 'SO202501150234',
      type: '退货退款',
      customerName: '张三',
      phone: '13800138000',
      status: '待审核',
      reason: '质量问题',
      description: '手机屏幕有划痕',
      refundAmount: 6999.00,
      refundMethod: '原路退回',
      applyTime: '2025-01-19 10:30:00',
      items: [
        {
          productName: '华为 Mate 60 Pro 12GB+512GB',
          specification: '曜金黑',
          quantity: 1,
          unitPrice: 6999.00
        }
      ],
      timeline: [
        {
          title: '提交售后申请',
          content: '客户提交售后申请',
          time: '2025-01-19 10:30:00',
          operator: '张三'
        }
      ]
    })
  },

  // 获取审批列表
  getApprovalList: async (params = {}) => {
    await delay()
    const data = [
      {
        id: 1,
        afterSalesNo: 'AS202501190001',
        orderNo: 'SO202501150234',
        type: '退货退款',
        customerName: '张三',
        refundAmount: 6999.00,
        reason: '质量问题',
        urgent: '紧急',
        applyTime: '2025-01-19 10:30:00',
        phone: '13800138000',
        refundMethod: '原路退回',
        description: '手机屏幕有划痕'
      }
    ]
    const paginatedData = mockPagination(data, params.page, params.pageSize)
    return mockResponse(paginatedData)
  },

  // 获取审批统计
  getApprovalStats: async () => {
    await delay()
    return mockResponse({
      pending: 15,
      approved: 23,
      rejected: 8,
      today: 6
    })
  },

  // 获取统计数据
  getAftersalesStatistics: async (params = {}) => {
    await delay()
    return mockResponse({
      kpi: {
        totalCount: 1256,
        countTrend: 8.5,
        totalRefund: 456780.50,
        refundTrend: -3.2,
        completionRate: 92.5,
        completionTrend: 5.6,
        avgHandleTime: 18.5,
        timeTrend: -12.3
      },
      trendData: [
        { date: '01-15', count: 48, amount: 3.12 },
        { date: '01-16', count: 41, amount: 2.69 },
        { date: '01-17', count: 38, amount: 2.25 },
        { date: '01-18', count: 52, amount: 3.53 },
        { date: '01-19', count: 45, amount: 2.86 }
      ],
      typeDistribution: [
        { name: '退货退款', value: 456 },
        { name: '仅退款', value: 312 },
        { name: '换货', value: 285 },
        { name: '维修', value: 203 }
      ],
      reasonAnalysis: [
        { reason: '质量问题', count: 389 },
        { reason: '商品破损', count: 234 },
        { reason: '发错货', count: 189 },
        { reason: '不想要了', count: 156 },
        { reason: '商品与描述不符', count: 125 },
        { reason: '收到假货', count: 78 },
        { reason: '其他', count: 45 }
      ]
    })
  },

  // 获取售后设置
  getSettings: async () => {
    await delay()
    return mockResponse({
      autoApprove: true,
      autoApproveAmount: 500,
      autoApproveTypes: ['仅退款'],
      applyDeadline: 7,
      returnDeadline: 7,
      defaultRefundMethod: '原路退回',
      refundDeadline: 3,
      enableRating: true,
      orderNoPrefix: 'AS'
    })
  },

  // 保存售后设置
  saveSettings: async (data) => {
    await delay()
    return mockResponse(data)
  },

  // 获取售后原因列表
  getReasonList: async () => {
    await delay()
    return mockResponse([
      { id: 1, type: '退货退款', reason: '质量问题', description: '商品存在质量问题', sort: 1, enabled: true },
      { id: 2, type: '退货退款', reason: '商品破损', description: '收到的商品有破损', sort: 2, enabled: true },
      { id: 3, type: '退货退款', reason: '发错货', description: '发货与订单不符', sort: 3, enabled: true },
      { id: 4, type: '仅退款', reason: '不想要了', description: '改变主意不想购买', sort: 4, enabled: true }
    ])
  },

  // 保存售后原因
  saveReason: async (data) => {
    await delay()
    return mockResponse({
      id: data.id || Date.now(),
      ...data
    })
  },

  // 删除售后原因
  deleteReason: async (id) => {
    await delay()
    return mockResponse({ id })
  },

  // 获取审批流程列表
  getWorkflowList: async () => {
    await delay()
    return mockResponse([
      {
        id: 1,
        name: '普通售后流程',
        type: '全部',
        minAmount: 0,
        maxAmount: 1000,
        approvers: ['客服主管'],
        enabled: true
      },
      {
        id: 2,
        name: '中等金额流程',
        type: '退货退款',
        minAmount: 1000,
        maxAmount: 5000,
        approvers: ['客服主管', '财务主管'],
        enabled: true
      }
    ])
  },

  // 保存审批流程
  saveWorkflow: async (data) => {
    await delay()
    return mockResponse({
      id: data.id || Date.now(),
      ...data
    })
  },

  // 删除审批流程
  deleteWorkflow: async (id) => {
    await delay()
    return mockResponse({ id })
  }
}

// 导出所有API
export default {
  userAPI,
  productAPI,
  supplierAPI,
  customerAPI,
  purchaseOrderAPI,
  salesOrderAPI,
  inventoryAPI,
  approvalAPI,
  systemAPI,
  statisticsAPI,
  uploadAPI,
  // 办公管理模块
  announcementAPI,
  notificationAPI,
  scheduleAPI,
  taskAPI,
  documentAPI,
  meetingAPI,
  officeApprovalAPI,
  contactAPI,
  workLogAPI,
  emailAPI,
  todoAPI,
  // 学习管理模块
  courseAPI,
  studyRecordAPI,
  examAPI,
  certificateAPI,
  knowledgeAPI,
  trainingPlanAPI,
  learningRankingAPI,
  courseManageAPI,
  examManageAPI,
  questionBankAPI,
  teacherManageAPI,
  learningSettingsAPI,
  // 售后管理模块
  aftersalesAPI
}
